import { random } from "./utils.js";
const view = document.getElementById("view");
const text = document.getElementById("text");
const colorInput = document.getElementById("color");
const sendBtn = document.getElementById("sendBtn");

let defaultDanmukuList = [
    "666",
    "2333",
    "有人吗",
    "你好",
    "XXX到此一游",
    "很好用的网站",
];
colorInput.value = "#ffffff";

// 设置新增div的class属性名
let index = 0;
sendBtn.onclick = function () {
    sendDanmuku();
    index++;
};

text.onfocus = function () {
    document.onkeydown = function (e) {
        if (e.key == "Enter") {
            sendDanmuku();
            index++;
        }
    };
};

function sendDanmuku(...isRandomShow) {
    // 设置弹幕的出现位置
    let top = Math.floor(Math.random() * 300);
    // 获取弹幕的颜色
    let color = colorInput.value.trim();
    // 获取弹幕的内容
    let content = text.value;
    if (content !== "") {
        defaultDanmukuList.push(content);
    }
    // console.log(defaultDanmukuList);
    defaultDanmukuList = [...new Set(defaultDanmukuList)];

    if (isRandomShow[0]) {
        content = defaultDanmukuList[random(0, defaultDanmukuList.length - 1)];
    }
    // 如果弹幕内容为空值，结束响应函数
    if (content == "") {
        return;
    }

    // 创建一个div作为弹幕的容器
    let newDiv = document.createElement("div");

    // 为创建的div增加class属性
    newDiv.className = "danmuku";

    // 将创建的div添加到view中
    view.appendChild(newDiv);

    // 获取创建的div
    let div = newDiv;
    div.style.backgroundColor = "transparent";
    div.style.color = color;
    div.style.display = "inline-block";
    div.style.width = 1200 + "px";
    div.style.height = 20 + "px";
    div.style.position = "absolute";
    div.style.top = top + "px";
    div.style.fontSize = random(16, 24) + "px";
    if (isRandomShow[0]) {
        div.style.right = -parseInt(div.style.width) + random(0, 100) + "px";
    }
    div.style.right = -parseInt(div.style.width) + "px";

    // 将获取到的弹幕内容添加到div中
    div.innerHTML = content;

    // 设置弹幕滑动计时器
    setTimeout(function () {
        div.style.right = 1200 + parseInt(div.style.width) + "px";
        div.style.transition = "all 15s linear";
    }, 0);
}

let autoSend = setInterval(function () {
    sendDanmuku(true);
}, 1000);
text.addEventListener("focusout", () => {
    autoSend = setInterval(function () {
        sendDanmuku(true);
    }, 1000);
});

text.addEventListener("focusin", () => {
    clearInterval(autoSend);
});
